public class Solution450 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode deleteNode(TreeNode root, int key) {
        if (root==null){
            return null;
        }
        TreeNode treeNode=new TreeNode(Integer.MIN_VALUE,root,null);
        dfs(treeNode,root,key);
        return treeNode.left;
    }

    private void dfs(TreeNode last, TreeNode pre,int key) {
        if (pre==null){
            return;
        }
        if (pre.val==key){
            if (pre.left==null && pre.right==null){
                if (last.left==pre){
                    last.left=null;
                }else{
                    last.right=null;
                }
            }else if (pre.left==null){
                TreeNode lst=pre;
                TreeNode pr=pre.right;
                while (pr.left!=null){
                    lst=pr;
                    pr=pr.left;
                }
                if (lst==pre){
                    pre.val=pre.right.val;
                    pre.right=pre.right.right;
                }else{
                    pre.val=pr.val;
                    lst.left=pr.right;
                }
            }else{
                TreeNode lst=pre;
                TreeNode pr=pre.left;
                while (pr.right!=null){
                    lst=pr;
                    pr=pr.right;
                }
                if (lst==pre){
                    pre.val=pre.left.val;
                    pre.left=pre.left.left;
                }else{
                    pre.val=pr.val;
                    lst.right=pr.left;
                }
            }
        }else{
            if (key<pre.val){
                dfs(pre,pre.left,key);
            }else{
                dfs(pre,pre.right,key);
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(new Solution450().deleteNode(new TreeNode(5,new TreeNode(3,new TreeNode(2),new TreeNode(4)),new TreeNode(6,null,new TreeNode(7))),3).left.val);
    }
}
